package eiisan.lock;

import java.util.Random;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * DelayQueue的简单使用
 *
 * @author eii
 * @time 2020/10/29 9:05 下午
 */
public class TestDelay {

    public static void main(String[] args) {
        //(1)创建delay队列
        DelayQueue<DelayItem> delayQueue = new DelayQueue<>();

        //(2)创建延迟任务
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            DelayItem delayItem = new DelayItem(random.nextInt(500),"task:" + i);
            delayQueue.offer(delayItem);
        }

        //(3)消费任务
        DelayItem item = null;
        try{
            for(;;){
                while ((item = delayQueue.take()) != null){
                    System.out.println(item.toString());
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }

    static class DelayItem implements Delayed {

        private final long delayTime;

        private final long expire;

        private final String taskName;

        public DelayItem(long delay, String taskName) {
            this.delayTime = delay;
            this.expire = System.currentTimeMillis() + delay;
            this.taskName = taskName;
        }

        /**
         * 剩余时间 = 到期时间 - 当前时间
         *
         * @param unit
         * @return
         */
        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(this.expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        /**
         * 优先级队列里优先级的规则
         *
         * @param o
         * @return
         */
        @Override
        public int compareTo(Delayed o) {
            return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        }

        @Override
        public String toString() {
            return "DelayItem{" +
                    "delayTime=" + delayTime +
                    ", expire=" + expire +
                    ", taskName='" + taskName + '\'' +
                    '}';
        }
    }


}
